package com.ymx.darling.wrapper.fragment;

import com.ymx.darling.bean.sql.BoundSql;
import com.ymx.darling.bean.sql.SqlParsingHelper;
import com.ymx.darling.util.StringLink;
import com.ymx.darling.bean.sql.SqlStatement;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 爱Java的小于
 */
public class UpdateSetSegment implements SqlSegment {
    /**
     * 保存set语句后的colum=value键值对
     */
    private final Map<String, Object> setMap = new HashMap<>();
    /**
     * 保存字段表达式 如 age = age + 1
     */
    private final StringLink columSetBuilder = new StringLink();
    /**
     * sql占位符参数
     */
    private final List<Object> params = new ArrayList<>();


    public UpdateSetSegment set(String colum, Object value){
        this.setMap.put(colum, value);
        return this;
    }

    public UpdateSetSegment setSegment(String columExpression, Object... param){
        BoundSql boundSql = SqlParsingHelper.parseSqlTemplate(columExpression, param);
        boundSql.bindSqlParameter();
        this.columSetBuilder.append(boundSql.getSql()).append(", ");
        this.params.addAll(boundSql.getBindParameters());

        return this;
    }


    @Override
    public SqlStatement getSqlStatement() {
        //将map集合中的元素放入set更新语句中
        for (Map.Entry<String,Object> colEntry : this.setMap.entrySet()) {
            this.columSetBuilder.append(colEntry.getKey())
                    .append(" = ?").append(", ");
            this.params.add(colEntry.getValue());
        }
        //去除最后一个逗号
        if (this.columSetBuilder.getNodeCount() > 0)
            this.columSetBuilder.deleteLast();
        String columExpression = this.columSetBuilder.toString();

        return new SqlStatement(columExpression, this.params);
    }
}
